import requests
import urllib

from typing import Any, Optional, Literal

from backend.blocks.github._auth import TEST_CREDENTIALS_INPUT, TEST_CREDENTIALS
from backend.data.block import Block, BlockOutput, BlockSchema
from backend.data.model import (
    APIKeyCredentials,
    OAuth2Credentials,
    Credentials,
    SchemaField, 
    CredentialsField, 
    CredentialsMetaInput
)
from backend.integrations.providers import ProviderName


class MyWikipediaSummaryBlock(Block):
    class Input(BlockSchema):
        topic: str = SchemaField(
            description="topic",
        )
        credentials: CredentialsMetaInput[
            Literal[ProviderName.GITHUB], Literal["api_key"]
        ] = CredentialsField(
            description="The GitHub integration can be used with "
            "any API key with sufficient permissions for the blocks it is used on.",
        )
        
    class Output(BlockSchema):
        summary: str = SchemaField(
            description="summary"
        )
        error: str = SchemaField(
            description="error"
        )

    @classmethod
    def get_request(
        cls, url: str, headers: Optional[dict] = None, json: bool = False
    ) -> Any:
        if headers is None:
            headers = {}
        
        response = requests.get(url, headers=headers)
        return response.json() if json else response.text
    
    def __init__(self):
        super().__init__(
            # Unique ID for the block, used across users for templates
            # If you are an AI leave it as is or change to "generate-proper-uuid"
            id="b05aa1e2-2ebc-4a7d-b71c-07802d6642bc",
            input_schema=MyWikipediaSummaryBlock.Input,  # Assign input schema
            output_schema=MyWikipediaSummaryBlock.Output,  # Assign output schema

            # Provide sample input, output and test mock for testing the block
            test_input={"topic": "Artificial Intelligence", "credentials": TEST_CREDENTIALS_INPUT},
            test_output=("summary", "summary content"),
            test_mock={"get_request": lambda url, json: {"extract": "summary content"}},
            test_credentials=TEST_CREDENTIALS,
        )

    def run(
        self, 
        input_data: Input, 
        *, 
        credentials: APIKeyCredentials, 
        **kwargs
    ) -> BlockOutput:
        try:
            topic = input_data.topic
            topic = urllib.parse.quote(topic, safe='/', encoding=None, errors=None)
            
            url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{topic}"

            response = self.get_request(url, json=True)

            yield "summary", response['extract']

        except requests.exceptions.HTTPError as http_err:
            raise RuntimeError(f"HTTP error occurred: {http_err}")

